import React, { useState, useEffect } from 'react';
import { Table, Button, Input, Switch, Space, Modal, Form, Radio, Checkbox } from 'antd';
import { SearchOutlined } from '@ant-design/icons';
import styles from './AccountManagement.module.css';
import { _apiAccountList ,_apiAccountAdd,_apiAccountDelete,_apiAccountUpdatePassword} from '../../../api';
import Notification, { showNotification } from '../../../components/message/message';

function AccountManagement() {
  const [selectedRowKeys, setSelectedRowKeys] = useState([]);
  const [isModalVisible, setIsModalVisible] = useState(false);
  const [loading, setLoading] = useState(false);
  const [tableData, setTableData] = useState([]);
  const [resetPasswordModalVisible, setResetPasswordModalVisible] = useState(false);
  const [currentUser, setCurrentUser] = useState(null);
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 10,
    total: 0,
  });

  const columns = [
    {
      title: 'ID',
      dataIndex: 'id',
      key: 'id',
      width: 80,
    },
    {
      title: '用户名',
      dataIndex: 'username',
      key: 'username',
    },
    {
      title: '真实姓名',
      dataIndex: 'realName',
      key: 'realName',
    },
    {
      title: '角色',
      dataIndex: 'role',
      key: 'role',
    },
    {
      title: '联系方式',
      dataIndex: 'phone',
      key: 'phone',
    },
    // {
    //   title: '账号状态',
    //   dataIndex: 'status',
    //   key: 'status',
    //   render: (status) => <Switch checked={status} />,
    // },
    {
      title: '操作',
      key: 'action',
      render: (_, record) => (
        <Space size="middle">
          <Button type="link" onClick={() => handleDelete(record.userId)}>删除</Button>
          <Button type="link" onClick={() => showResetPasswordModal(record)}>重置密码</Button>
        </Space>
      ),
    },
  ];

  // 获取账号列表数据
  const fetchAccountList = async (params = {}) => {
    try {
      setLoading(true);
      const { current = 1, pageSize = 10 } = params;
      const response = await _apiAccountList({
        page: current,
        pageSize,
        ...params,
      });
      
      // 转换数据结构以匹配表格需求
      const formattedData = response.data.map(item => ({
        key: item.id,  // antd Table需要key属性
        id: item.id,
        userId: item.userId,  // 添加 userId 字段
        username: item.userName,
        realName: item.realName,
        role: item.roleId === 3 ? '超级管理员' : item.roleId === 2 ? '系统管理员' : '普通账户',  // 根据roleId转换角色显示
        phone: item.phone,
        status: item.status === 0 ? false : true,  // 转换状态为boolean
      }));
      
      setTableData(formattedData);
      setPagination({
        ...pagination,
        current,
        pageSize,
        total: response.total || 0,  // 根据实际接口返回结构调整
      });
    } catch (error) {
      console.error('获取账号列表失败:', error);
    } finally {
      setLoading(false);
    }
  };

  // 组件挂载时获取数据
  useEffect(() => {
    fetchAccountList();
  }, []);

  // 处理表格变化（分页、排序、筛选）
  const handleTableChange = (newPagination, filters, sorter) => {
    fetchAccountList({
      current: newPagination.current,
      pageSize: newPagination.pageSize,
      sortField: sorter.field,
      sortOrder: sorter.order,
      ...filters,
    });
  };

  const onSelectChange = (newSelectedRowKeys) => {
    setSelectedRowKeys(newSelectedRowKeys);
  };

  const rowSelection = {
    selectedRowKeys,
    onChange: onSelectChange,
  };

  const showModal = () => {
    setIsModalVisible(true);
  };

  const handleCancel = () => {
    setIsModalVisible(false);
  };

  const handleOk = async (values) => {
    try {
      const roleIdMap = {
        'normal': 1,
        'system': 2,
        'super': 3
      };
      
      const submitData = {
        ...values,
        roleId: roleIdMap[values.role],
        status: 0,
        avatar: null,
        realName: values.realName,
        isAudit: 0
      };
      
      const response = await _apiAccountAdd(submitData);
      if (response.status === 200 || response.code === 200) {
        setIsModalVisible(false);
        showNotification("添加成功",'success');
        // 刷新表格数据
        fetchAccountList({
          current: pagination.current,
          pageSize: pagination.pageSize
        });
      } else {
        showNotification("添加失败",'error');
      }
    } catch (error) {
      console.error('添加用户失败:', error);
      showNotification("添加失败",'error');
    }
  };

  // 修改删除处理函数
  const handleDelete = async (userId) => {
    try {
      const response = await _apiAccountDelete({ userId });  // 直接传递 userId
      if (response.status === 204 || response.code === 204) {
        showNotification("删除成功",'success');
        fetchAccountList({
          current: pagination.current,
          pageSize: pagination.pageSize
        });
      } else {
        showNotification("删除失败",'error');
      }
    } catch (error) {
      console.error('删除用户失败:', error);
      showNotification("删除失败",'error');
    }
  };

  // 显示重置密码模态框
  const showResetPasswordModal = (user) => {
    setCurrentUser(user);
    setResetPasswordModalVisible(true);
  };

  // 关闭重置密码模态框
  const handleResetPasswordCancel = () => {
    setResetPasswordModalVisible(false);
    setCurrentUser(null);
  };

  // 处理密码重置
  const handleResetPassword = async (values) => {
    try {
      const response = await _apiAccountUpdatePassword({
        userId: currentUser.userId,
        password: values.currentPassword,
        newPassword: values.newPassword,
        confirmPassword: values.confirmPassword
      });
      
      if (response.status === 204 || response.code === 204) {
        setResetPasswordModalVisible(false);
        setCurrentUser(null);
        showNotification("密码重置成功", 'success');
      } else {
        showNotification("密码重置失败", 'error');
      }
    } catch (error) {
      console.error('重置密码失败:', error);
      showNotification("重置密码失败", 'error');
    }
  };

  return (
    <div className={styles.container}>
      <Notification />
      <div className={styles.header}>
        <h2>当前位置: 账号管理</h2>
      </div>
      <div className={styles.toolbar}>
        <div className={styles.buttons}>
          <Button type="primary" onClick={showModal}>新增</Button>
          {/* <Button>禁用</Button>
          <Button>启用</Button>
          <Button>删除</Button> */}
        </div>
        <Input
          placeholder="请输入用户名、真实姓名"
          suffix={<SearchOutlined />}
          className={styles.search}
        />
      </div>
      <Table
        loading={loading}
        rowSelection={rowSelection}
        columns={columns}
        dataSource={tableData}
        pagination={pagination}
        onChange={handleTableChange}
      />

      <Modal
        title="新增用户"
        open={isModalVisible}
        onCancel={handleCancel}
        footer={null}
      >
        <Form onFinish={handleOk} layout="vertical">
          <Form.Item
            label="用户名"
            name="username"
            rules={[{ required: true, message: '请输入用户名' }]}
          >
            <Input placeholder="请输入" />
          </Form.Item>

          <Form.Item
            label="密码"
            name="password"
            rules={[{ required: true, message: '请输入密码' }]}
          >
            <Input.Password placeholder="6-18个字母数字组合" />
          </Form.Item>

          <Form.Item
            label="真实姓名"
            name="realName"
            rules={[{ required: true, message: '请输入真实姓名' }]}
          >
            <Input placeholder="请输入" />
          </Form.Item>

          <Form.Item
            label="手机号"
            name="phone"
            rules={[{ required: true, message: '请输入手机号' }]}
          >
            <Input placeholder="请输入" />
          </Form.Item>

          <Form.Item
            label="邮箱"
            name="email"
            rules={[
              { required: true, message: '请输入邮箱' },
              { type: 'email', message: '请输入有效的邮箱地址' }
            ]}
          >
            <Input placeholder="请输入邮箱" />
          </Form.Item>

          <Form.Item
            label="角色"
            name="role"
            rules={[{ required: true, message: '请选择角色' }]}
          >
            <Radio.Group>
              <Radio value="normal">普通账户</Radio>
              <Radio value="system">系统管理员</Radio>
              <Radio value="super">超级管理员</Radio>
            </Radio.Group>
          </Form.Item>

          <Form.Item>
            <Space style={{ float: 'right' }}>
              <Button onClick={handleCancel}>取消</Button>
              <Button type="primary" htmlType="submit">提交</Button>
            </Space>
          </Form.Item>
        </Form>
      </Modal>

      {/* 重置密码模态框 */}
      <Modal
        title="重置密码"
        open={resetPasswordModalVisible}
        onCancel={handleResetPasswordCancel}
        footer={null}
      >
        <Form onFinish={handleResetPassword} layout="vertical">
          <Form.Item
            label="当前密码"
            name="currentPassword"
            rules={[{ required: true, message: '请输入当前密码' }]}
          >
            <Input.Password placeholder="请输入当前密码" />
          </Form.Item>

          <Form.Item
            label="新密码"
            name="newPassword"
            rules={[{ required: true, message: '请输入新密码' }]}
          >
            <Input.Password placeholder="请输入新密码" />
          </Form.Item>

          <Form.Item
            label="确认密码"
            name="confirmPassword"
            rules={[
              { required: true, message: '请确认新密码' },
              ({ getFieldValue }) => ({
                validator(_, value) {
                  if (!value || getFieldValue('newPassword') === value) {
                    return Promise.resolve();
                  }
                  return Promise.reject(new Error('两次输入的密码不一致'));
                },
              }),
            ]}
          >
            <Input.Password placeholder="请再次输入新密码" />
          </Form.Item>

          <Form.Item>
            <Space style={{ float: 'right' }}>
              <Button onClick={handleResetPasswordCancel}>取消</Button>
              <Button type="primary" htmlType="submit">提交</Button>
            </Space>
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
}

export default AccountManagement;